"""
区域管理数据模型
对应数据库表: base_region_province, base_region_city, base_region_area
用于数据库操作和业务逻辑处理
"""
from datetime import datetime
from typing import Optional, List

from pydantic import BaseModel, Field, ConfigDict


class RegionBaseModel(BaseModel):
    """区域基础数据模型"""
    code: str = Field(..., description="国标6位编码，不足位补零", max_length=6)
    name: str = Field(..., description="区域名称", max_length=64)
    level: int = Field(..., description="层级：1=省，2=市，3=区县", ge=1, le=3)
    gmt_create: datetime = Field(..., description="创建时间")
    gmt_update: datetime = Field(..., description="更新时间")

    model_config = ConfigDict(from_attributes=True)


class Province(RegionBaseModel):
    """省份数据模型"""
    id: int = Field(..., description="主键ID")
    level: int = Field(1, description="层级：1=省")

    # 移除过于严格的验证，允许各种格式的省份编码
    # 实际数据中可能存在不同的编码格式


class City(RegionBaseModel):
    """城市数据模型"""
    id: int = Field(..., description="主键ID")
    province_code: str = Field(..., description="所属省份编码", max_length=6)
    level: int = Field(2, description="层级：2=市")

    # 移除过于严格的验证，允许各种格式的城市编码


class Area(RegionBaseModel):
    """区县数据模型"""
    id: int = Field(..., description="主键ID")
    city_code: str = Field(..., description="所属城市编码", max_length=6)
    level: int = Field(3, description="层级：3=区县")


class RegionStats(BaseModel):
    """区域统计信息模型"""
    total_provinces: int = Field(0, description="省份总数")
    total_cities: int = Field(0, description="城市总数")
    total_areas: int = Field(0, description="区县总数")
    provinces_with_cities: int = Field(0, description="有城市的省份数")
    cities_with_areas: int = Field(0, description="有区县的城市数")

    model_config = ConfigDict(from_attributes=True)


class RegionHierarchy(BaseModel):
    """区域层级关系模型"""
    province: Optional[Province] = Field(None, description="省份信息")
    city: Optional[City] = Field(None, description="城市信息")
    area: Optional[Area] = Field(None, description="区县信息")

    model_config = ConfigDict(from_attributes=True)


class RegionWithChildren(BaseModel):
    """带子区域的区域模型"""
    region: RegionBaseModel = Field(..., description="区域信息")
    children: List['RegionWithChildren'] = Field(default_factory=list, description="子区域列表")
    children_count: int = Field(0, description="子区域数量")

    model_config = ConfigDict(from_attributes=True)


# 让Pydantic正确处理自引用
RegionWithChildren.model_rebuild()